<template>
  <el-dialog ref="wf-dialog"
             custom-class="wf-dialog"
             :visible.sync="visible"
             title="人员选择"
             width="60%"
             :before-close="handleClose"
             append-to-body>

    <div style="margin-bottom:20px">
      <el-switch
        v-model="queryType"
        active-text="根据查询权限"
        inactive-text="根据区划"
        active-value="1"
        inactive-value="2">
      </el-switch>
    </div>
    <div>
      <avue-crud v-if="isInit && visible"
                 :key="key"
                 :option="option"
                 :table-loading="loading"
                 :data="data"
                 :page.sync="page"
                 v-model="form"
                 ref="crudUser"
                 @search-change="searchChange"
                 @search-reset="searchReset"
                 @selection-change="selectChange"
                 @current-change="page.currentPage=$event"
                 @size-change="page.pageSize=$event"
                 @row-click="rowClick"
                 @on-load="onLoad">
        <template v-if="checkType == 'radio'"
                  #radio="{row}">
          <el-radio v-model="form.radio"
                    :label="row.id"><i></i></el-radio>
        </template>
      </avue-crud>
    </div>
    <span slot="footer"
          class="dialog-footer">
      <el-button @click="handleClose"
                 size="mini">取 消</el-button>
      <el-button type="primary"
                 @click="handleConfirm"
                 size="mini">确 定</el-button>
    </span>

  </el-dialog>
</template>
<script>
import {getRegionList} from "@/api/system/region";
import {validatenull} from "@/util/validate";
import {getLazyTree as getAreaTree, areaLazyTree} from "@/api/base/region";

export default {
  props: {
    defaultChecked: String,
    userUrl: {
      type: String,
      default: () => {
        return '/api/blade-user/search/user'
      }
    },
    customOption: Object,
    checkType: {
      type: String,
      default: () => {
        return 'radio'
      }
    }
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.number = 1;
        }
      }
    },
    checkType: {
      handler(val) {
        if (val == 'radio') {
          this.$set(this.option, 'selection', false)
          this.findObject(this.option.column, 'radio').hide = false
        } else {
          this.$set(this.option, 'selection', true)
          this.findObject(this.option.column, 'radio').hide = true
        }
      },
      immediate: true
    },
    queryType: {
      handler(val) {
        this.query = {
          queryType: val
        };
        const areaCode = this.findObject(this.option.column, 'areaCode');
        //根据查询权限
        if (val != "2") {
          areaCode.hide = true;
          areaCode.search = false;
        } else {
          //根据区划
          areaCode.hide = false;
          areaCode.search = true;
        }
        this.page.currentPage = 1;
        this.onLoad(this.page, {change: true});
      }
    }
  },
  computed: {
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
    names() {
      let names = [];
      this.selectionList.forEach(ele => {
        names.push(ele.realName);
      });
      return names.join(",");
    },
    deptIds() {
      let deptIds = [];
      this.selectionList.forEach(ele => {
        deptIds.push(ele.deptId)
      });
      return deptIds.join(",")
    },
    deptNames() {
      let deptNames = [];
      this.selectionList.forEach(ele => {
        deptNames.push(ele.deptName)
      });
      return deptNames.join(",")
    },
    deptCodes() {
      let deptCodes = [];
      this.selectionList.forEach(ele => {
        deptCodes.push(ele.deptCode)
      });
      return deptCodes.join(",")
    },
    accounts() {
      let accounts = [];
      this.selectionList.forEach(ele => {
        accounts.push(ele.account)
      });
      return accounts.join(",")
    },
    thirdIds() {
      let thirdIds = [];
      this.selectionList.forEach(ele => {
        thirdIds.push(ele.thirdId)
      });
      return thirdIds.join(",")
    }
  },
  data() {
    return {
      queryType: "1",
      key: 0,
      number: 1,
      isInit: false,
      visible: false,
      form: {},
      query: {},
      loading: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      data: [],
      props: {
        id: 'id',
        name: 'realName',
        records: 'data.data.records',
        total: 'data.data.total',
      },
      option: {
        size: 'mini',
        searchSize: 'mini',
        align: 'center',
        menu: false,
        addBtn: false,
        header: false,
        border: true,
        tip: false,
        reserveSelection: true,
        highlightCurrentRow: true,
        gutter: 5,
        searchMenuSpan: 6,
        selection: true,
        column: [{
          label: '',
          prop: 'radio',
          type: 'radio',
          width: 55,
          hide: true
        }, {
          label: '头像',
          prop: 'avatar',
          type: 'upload',
          width: 90,
          hide: true
        }, {
          label: "区划",
          prop: "areaCode",
          type: "tree",
          dicUrl: "/api/blade-system/regioin/areaLazyTree?parentCode=000000000000",
          props: {
            label: "name",
            value: 'code'
          },
          search: false,
          hide: true,
          lazy: true,
          treeLoad: (node, resolve) => {
            let parentId = node.data.code;
            let isHasChildren = node.data.hasChildren;
            let list = [];
            let callback = () => {
              resolve((list || []).map(ele => {
                return Object.assign(ele, {
                  leaf: ele.code.substring(4, 6) != '00' || !ele.hasChildren
                })
              }));
            }
            if (node.level == 0 || isHasChildren != 0) {
              if (parentId === undefined) {
                areaLazyTree("000000000000").then(res => {
                  list = res.data.data
                  callback()
                });
              } else {
                areaLazyTree(parentId).then(res => {
                  list = res.data.data;
                  callback()
                });
              }
            } else {
              list = [];
              callback()
            }
          },
        }, {
          label: '姓名',
          prop: 'realName',
          overHidden: true,
          search: true
        }, {
          label: '账号',
          prop: 'account',
          overHidden: true,
          search: true
        }, {
          label: '部门',
          prop: 'deptName',
          overHidden: true,
          search: false,
        },
          {
            label: "部门",
            prop: "deptId",
            type: "tree",
            props: {
              label: "name",
              value: 'code'
            },
            rules: [{
              required: true,
              message: "请选择所属部门",
              trigger: "click"
            }],
            hide: true,
            dicUrl: `/api/blade-system/regioin/regionList?parentCode=000000000000&provinceCode=62`,
            search: true,
            lazy: true,
            treeLoad: (node, resolve) => {
              let parentId = node.data.code;
              let isHasChildren = node.data.hasChildren;
              let list = [];
              let callback = () => {
                resolve((list || []).map(ele => {
                  return Object.assign(ele, {
                    leaf: !ele.hasChildren,
                  })
                }));
              }
              if (node.level == 0 || isHasChildren != 0) {
                if (parentId === undefined) {
                  getRegionList("000000000000").then(res => {
                    list = res.data.data;
                    list.forEach(item => {
                      if (item.dataType == 'dept') {
                        item.disabled = false;
                      } else {
                        item.disabled = true;
                      }
                    });
                    callback()
                  });
                } else {
                  getRegionList(parentId).then(res => {
                    list = res.data.data;
                    list.forEach(item => {
                      if (item.dataType == 'dept') {
                        item.disabled = false;
                      } else {
                        item.disabled = true;
                      }
                    });
                    callback()
                  });
                }
              } else {
                list = [];
                callback()
              }
            },
          }]
      }
    }
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      if (!this.isInit) {
        if (this.customOption) {
          const {column, userProps} = this.customOption
          if (column) this.$set(this.option, 'column', column)
          if (userProps) this.$set(this, 'props', userProps)
        }
        this.isInit = true
      }
    },
    handleConfirm() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据")
        return
      }
      // let params = {
      //   value: this.ids,
      //   text: this.names,
      //   deptIds: this.deptIds,
      //   deptNames: this.deptNames,
      //   deptCodes: this.deptCodes,
      //   accounts: this.accounts,
      //   thirdIds: this.ids,
      // }
      // this.$emit('onConfirm', params)
      this.$emit('onConfirm', this.ids, this.names, this.deptIds, this.deptNames, this.deptCodes, this.accounts, this.thirdIds)

      this.handleClose()
    },
    handleClose(done) {
      // this.selectionClear()
      this.visible = false
      if (done && typeof done == 'function') done()
      this.searchReset();
      this.page.currentPage = 1;
      this.selectionList = [];
      this.key++;
      this.queryType = "1";

    },
    searchReset() {
      this.query = {}
      this.onLoad(this.page)
    },
    searchChange(params, done) {
      this.query = params
      this.page.currentPage = 1
      this.onLoad(this.page, params)
      done()
    },
    selectionClear() {
      this.selectionList = []
      if (this.$refs.crudUser) this.$refs.crudUser.toggleSelection()
    },
    rowClick(row) {
      if (this.checkType == 'radio') {
        this.selectionList = [row]
        this.$set(this.form, 'radio', row.id)
      } else this.$refs.crudUser.toggleSelection([row])
    },
    changeDefaultChecked() {
      let defaultChecked = this.defaultChecked
      if (!this.defaultChecked) defaultChecked = ''

      if (this.checkType == 'checkbox') {
        this.selectionClear()
        const checks = defaultChecked.split(",")
        if (checks.length > 0) {
          setTimeout(() => {
            checks.forEach(c => {
              const row = this.data.find(d => d.id == c)
              if (row && this.$refs.crud) this.$refs.crud.toggleRowSelection(row, true)
            })
          }, 500);
        }
      } else {
        const row = this.data.find(d => d.id == defaultChecked)
        if (row) {
          this.selectionList = [row]
          this.$set(this.form, 'radio', defaultChecked)
        } else {
          this.selectionList = []
          this.$set(this.form, 'radio', '')
        }
      }
    },
    onLoad(page, params = {}) {
      this.loading = true;
      const that = this;
      const param = {
        current: page.currentPage,
        size: page.pageSize,
        ...Object.assign(params = {
          status: 1,
          isDeleted: 0,
          queryType: this.queryType,
          change: params.change
        }, this.query)
      }
      this.$axios.get(this.userUrl, {params: param}).then(res => {
        this.page.total = this.getAsVal(res, this.props.total)
        this.data = this.getAsVal(res, this.props.records) || []
        this.loading = false;
        if (this.number == 1) {
          this.initDefaultChecked();
          this.number++;
        }
        if (param.change) {
          that.$refs.crudUser.toggleSelection(that.selectionList);
        }
      })
    },
    getAsVal(obj, bind = '') {
      let result = this.deepClone(obj)
      if (this.validatenull(bind)) return result
      bind.split('.').forEach(ele => {
        if (!this.validatenull(result[ele])) {
          result = result[ele]
        } else {
          result = ''
        }
      });
      return result
    },
    selectChange(list) {
      this.selectionList = list;
    },
    initDefaultChecked() {
      let that = this;
      if (!validatenull(that.defaultChecked.value)) {
        let linkUserIds = that.defaultChecked.value.split(",");
        let thirdIds = that.defaultChecked.thirdIds.split(",");
        let deptCodes = that.defaultChecked.deptCodes.split(",");
        let accounts = that.defaultChecked.accounts.split(",");
        let linkUserNames = that.defaultChecked.text.split(",");
        let linkDeptIds = that.defaultChecked.deptIds.split(",");
        let linkDeptNames = that.defaultChecked.deptNames.split(",");
        if (linkUserIds.length > 0) {
          linkUserIds.forEach((item, index) => {
            let obj = {
              id: item,
              deptId: linkDeptIds[index],
              deptName: linkDeptNames[index],
              realName: linkUserNames[index],
              deptCode: deptCodes[index],
              account: accounts[index],
              thirdId: thirdIds[index]
            }
            that.selectionList.push(obj);
          });
          that.$refs.crudUser.toggleSelection(that.selectionList);
        }
      }
    }
  }
}
</script>
<style lang="scss">
.wf-dialog {
  display: flex;
  flex-direction: column;
  margin: 0 !important;
  position: absolute;
  top: 40%;
  left: 50%;
  transform: translate(-50%, -40%);
  max-height: calc(100% - 30px);
  max-width: calc(100% - 30px);

  .el-dialog__body {
    flex: 1;
    overflow: auto;
  }
}
</style>
